using UnityEngine;

namespace Jerry.UiFrame
{
    public class JWindow : MonoBehaviour, IComponent
    {
        [SerializeField]
        [Header("是否启用安全区域")]
        private bool bEnableSafeArea = false;
        private RectTransform _rectTransform;

        private Rect _lastSafeArea = new Rect(0, 0, 0, 0);
        private void Awake()
        {
            _rectTransform = GetComponent<RectTransform>();
        }

        private void Start()
        {
            if (bEnableSafeArea)
            {
                _lastSafeArea = Screen.safeArea;
                ApplySafeArea();
            }
        }

        private void Update()
        {
            if (!bEnableSafeArea)
                return;
            if (Screen.safeArea == _lastSafeArea)
                return;
            ApplySafeArea();
        }

        /// <summary>
        /// 应用安全区域
        /// </summary>
        private void ApplySafeArea()
        {
            var r = Screen.safeArea;
            _lastSafeArea = r;
            Vector2 anchorMin = r.position;
            Vector2 anchorMax = r.position + r.size;
            anchorMin.x /= Screen.width;
            anchorMin.y /= Screen.height;
            anchorMax.x /= Screen.width;
            anchorMax.y /= Screen.height;
            _rectTransform.anchorMin = anchorMin;
            _rectTransform.anchorMax = anchorMax;
        }

        public void SetVisible(bool bVisible)
        {
            gameObject.SetActive(bVisible);
        }

        public T GetChild<T>(string childName) where T : IComponent
        {
            var comp = transform.Find(childName).GetComponent<IComponent>();
            return (T)comp;
        }
    }
}